package com.yyz.lease.web.admin.schedule;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yyz.lease.common.constant.RedisConstant;
import com.yyz.lease.model.entity.LeaseAgreement;
import com.yyz.lease.model.enums.LeaseStatus;
import com.yyz.lease.web.admin.service.LeaseAgreementService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

/**
 * 定时任务
 */
@Component
@RequiredArgsConstructor
public class ScheduledTasks {
    private final LeaseAgreementService service;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 每天判定租期是否过期
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void checkLeaseStatus() {
        LambdaUpdateWrapper<LeaseAgreement> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.le(LeaseAgreement::getLeaseEndDate, new Date());
        updateWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED, LeaseStatus.WITHDRAWING);
        updateWrapper.set(LeaseAgreement::getStatus, LeaseStatus.EXPIRED);
        service.update(updateWrapper);
    }

    /**
     * 每天删除缓存
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void deleteRedis() {
        Set<String> keys = redisTemplate.keys(RedisConstant.APP_ROOM_PREFIX + "*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }
}
